package threadpoolnio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author ：xx
 * @date ：Created in 2020/3/11 20:50
 * @description：
 * @modified By：
 */
public class NIOTest {
    public static void main(String[] args) {
//        IOTest();
        NIOTest();
    }

    private static void NIOTest() {
        FileInputStream in=null;
        FileOutputStream out=null;
        try {
            in=new FileInputStream("test.txt");
            out=new FileOutputStream("out.txt");
            //拿到通道
            FileChannel channel = in.getChannel();
            FileChannel outChannel=out.getChannel();
            //开辟缓冲区
            ByteBuffer buff=ByteBuffer.allocate(1024);
            //读数据
            int count=channel.read(buff);
            System.out.println("readcount:"+count);
            while (count!=-1){
                buff.flip();
                while (buff.hasRemaining()){
                    System.out.print((char)buff.get());
                }
                buff.flip();
                outChannel.write(buff);
                buff.compact();
                count=channel.read(buff);
            }
            System.out.println();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(in!=null)
                    in.close();
                if(out!=null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void IOTest() {
        InputStream in = null;
        try{
            in = new BufferedInputStream(new FileInputStream("test.txt"));
            byte [] buf = new byte[1024];
            int bytesRead = in.read(buf);
            while(bytesRead != -1)
            {
                for(int i=0;i<bytesRead;i++)
                    System.out.print((char)buf[i]);
                bytesRead = in.read(buf);
            }
            System.out.println();
        }catch (IOException e)
        {
            e.printStackTrace();
        }finally{
            try{
                if(in != null){
                    in.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
